package com.blog.web;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.blog.dao.UserDAO;
import com.blog.domain.User;
import com.blog.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private UserService userService;
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public UserService getUserService() {
		return userService;
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping("/login")
	public String login(@ModelAttribute User user, HttpServletRequest request) {
		List<User> list = userDAO.executeQuery("from User where username = ? and password = ?", user.getUsername(), user.getPassword());
		if (null == list || 0 == list.size()) {
			return "login";
		}
		request.getSession().setAttribute("user", list.get(0));
		return "redirect:/";
	}
	
	@RequestMapping("/logoff")
	public String logoff(HttpServletRequest request) {
		request.getSession().removeAttribute("user");
		return "redirect:/";
	}
	
	@RequestMapping("/register")
	public String register(@ModelAttribute User user, HttpServletRequest request) {
		Set<User> list = userDAO.findUserByUsername(user.getUsername());
		if(null == list || list.size() == 0) {
			userService.saveUser(user);
			request.getSession().setAttribute("user", user);
			return "redirect:/";
		}
		return "userExist";
	}
	
	@RequestMapping("/accessError")
	public String accessError() {
		return "accessError";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
}
